/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package command.linux;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.logging.Level;
import java.util.logging.Logger;

import command.Command;

import config.Debug;
import config.Settings;
import controller.ScheduleController;

/**
 * 
 * @author Yang Wang <yang@digitalmenubox.com>
 */
public class rebootSystem implements Command {

	@Override
	public void execute(String[] args) {
		try {
			Debug.log("Restarting Computer...", Debug.SYSTEM_LEVEL);
			copyClassLoaderFile();
			ProcessBuilder pb = new ProcessBuilder(new File(Settings.getScriptDirectory()).getAbsolutePath() + File.separator + "reboot.sh");
			Process p = pb.start();

		} catch (IOException ex) {
			Logger.getLogger(rebootSystem.class.getName()).log(Level.SEVERE, null, ex);
		}
	}

	public static void main(String[] args) {
	}

	public static void copyClassLoaderFile() {
		File rebootScript = new File(Settings.getScriptDirectory(), "reboot.sh");
		InputStream is = null;
		InputStreamReader isr = null;
		BufferedReader br = null;
		BufferedWriter bw = null;
		if (!rebootScript.exists()) {
			try {
				is = ScheduleController.class.getClassLoader().getResourceAsStream("appdata/scripts/reboot.sh");
				isr = new InputStreamReader(is);
				br = new BufferedReader(isr);
				rebootScript.createNewFile();
				bw = new BufferedWriter(new FileWriter(rebootScript));
				String line = null;
				while ((line = br.readLine()) != null) {
					bw.write(line);
				}
				bw.flush();
				rebootScript.setExecutable(true);
			} catch (IOException ex) {
				Logger.getLogger(rebootSystem.class.getName()).log(Level.SEVERE, null, ex);
			} finally {
				try {
					isr.close();
					br.close();
					bw.close();
				} catch (IOException ex1) {
					Logger.getLogger(rebootSystem.class.getName()).log(Level.SEVERE, null, ex1);
				}
			}
		}
	}
}
